package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.util.List;

/**
 * @author cheng
 * @since 2021/7/4
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {

        // 将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);

        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回多条");
        }
    }

    @Override
    public Integer addOne(String statementid, Object... params) throws Exception {

        // 对add方法进行调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Integer addNum = simpleExecutor.update(configuration, mappedStatement, params);
        return addNum;
    }

    @Override
    public Integer updateOne(String statementid, Object... params) throws Exception {

        // 对update方法进行调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Integer updateNum = simpleExecutor.update(configuration, mappedStatement, params);
        return updateNum;
    }

    @Override
    public Integer deleteOne(String statementid, Object... params) throws Exception {

        // 对delete方法进行调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Integer deleteNum = simpleExecutor.update(configuration, mappedStatement, params);
        return deleteNum;
    }


}
